package cn.hanna.springcloudalibaba.controller;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.TimeUnit;

/**
 * @author smileha
 * @create 2021-10-21 17:52
 * @description
 */
@RestController
@Slf4j
public class SentinelServiceController {

    @GetMapping("/payment/sentinel/testA")
    public String testA(){
        return "........testA";
    }

    @GetMapping("/payment/sentinel/testB")
    public String testB() throws InterruptedException {
//        TimeUnit.SECONDS.sleep(1);
        log.info(Thread.currentThread().getName()+"--------------");
        return "........testB";
    }

    @GetMapping("/payment/sentinel/testC")
    public String testC() throws InterruptedException {
//        TimeUnit.SECONDS.sleep(1);
        int i = 10/0;
        log.info(Thread.currentThread().getName()+"--------------");
        return "........testC";
    }

    // 对热点key进行限流
    @GetMapping("/payment/sentinel/testD")
    @SentinelResource(value = "hotKey",blockHandler = "handleHotKey")
    public String testD(@RequestParam(value = "p1",required = false) String p1,
                        @RequestParam(value = "p2",required = false) String p2) throws InterruptedException {
        int i = 10 / 0;
        return "........testD";
    }

    // 此处注意一定要传入与上述方法相同的参数，并且传入BlockException异常对象
    public String handleHotKey(String p1,String p2,BlockException blockException){
        return "该热点资源访问过于频繁，请稍后再试~~~";
    }
}
